﻿using CCWin;
using ERP_SaaS_WinForm.物料管理.Material;
using ERP_SaaS_WinForm.生产工单_报工_工序.Process;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.生产工单_报工_工序
{
    public partial class ProcessForm : CCSkinMain
    {
        private string urls;
        // 分页参数
        private int currentPageIndex = 1;
        private int pageSize = 15;
        private int totalCount = 0;
        private int totalPage = 0;
        
        // 筛选参数 - 只保留检验单号筛选
        private string filterInspectionOrderCode = "";
        
        // 生产工单筛选参数
        private string ordersFilterCode = "";
        private string ordersFilterName = "";
        private string ordersFilterProductName = "";
        private string ordersFilterState = "";
        
        // 加载状态
        private bool isLoading = false;
        // 是否在工序面板中显示生产工单（否则显示工序）
        private bool showingOrders = false;

        // 生产工单界面控件（运行时创建，避免修改设计器）
        private Panel panelOrders;
        private Panel panelOrdersFilter;
        private Panel panelOrdersPaging;
        private DataGridView dgvOrders;
        private TextBox txtOrdersCode;
        private TextBox txtOrdersName;
        private TextBox txtOrdersProductName;
        private ComboBox cboOrdersState;
        private Button btnOrdersSearch;
        private Button btnOrdersReset;
        private Button btnOrdersSchedule;
        private Button btnOrdersFirst;
        private Button btnOrdersPrev;
        private Button btnOrdersNext;
        private Button btnOrdersLast;
        private ComboBox cboOrdersPageSize;
        private Label lblOrdersTotal;
        private Label lblOrdersPage;

        public ProcessForm()
        {
            InitializeComponent();
            InitializeReportControls();
            urls = Apllo.ApiBaseUrl;
        }

        private string GetProcessStateText(int state)
        {
            return state == 0 ? "启用" : "禁用";
        }

        // 追加一行工序信息（带颜色和对齐优化）
        private void AppendProcessRow(RichTextBox box, ProcessTable item)
        {
            if (box == null || item == null) return;
            var stateText = GetProcessStateText(item.State);

            // 行首颜色：启用绿色，禁用红色
            var color = item.State == 0 ? Color.FromArgb(34, 139, 34) : Color.FromArgb(178, 34, 34);
            int start = box.TextLength;
            string row = string.Format("{0,-8} {1,-12} {2,-15} {3,-8} {4,-20} {5,-20}\n",
                item.ProcessId,
                item.ProcessCode ?? "",
                item.ProcessName ?? "",
                stateText,
                (item.ProcessDescription ?? "").Length > 18 ? (item.ProcessDescription ?? "").Substring(0, 18) + ".." : (item.ProcessDescription ?? ""),
                (item.Remark ?? "").Length > 18 ? (item.Remark ?? "").Substring(0, 18) + ".." : (item.Remark ?? "")
            );
            box.AppendText(row);
            int end = box.TextLength;
            box.Select(start, end - start);
            box.SelectionColor = color;
            box.Select(end, 0);
        }



        private void ProcessForm_Load(object sender, EventArgs e)
        {
            // 默认显示工序面板
            ShowProcessPanel();
            _ = LoadProcessesAsync();
            
            // 测试操作列显示
            Console.WriteLine("ProcessForm加载完成，开始测试操作列...");
            if (dgvOrders != null)
            {
                Console.WriteLine($"dgvOrders列数: {dgvOrders.Columns.Count}");
                EnsureOrdersActionColumn();
                Console.WriteLine($"确保操作列后，列数: {dgvOrders.Columns.Count}");
            }
        }

        private void InitializeReportControls()
        {
            
            // 设置默认页大小
            cboReportPageSize.SelectedIndex = 0;
            pageSize = 15; // 确保pageSize变量被正确初始化
            
            // 设置筛选框的提示文本
            txtProductionOrdersCode.Text = "输入检验单号";
            txtProductionOrdersCode.ForeColor = Color.Gray;
            
            // 绑定事件
            btnReportSearch.Click += BtnReportSearch_Click;
            btnReportReset.Click += BtnReportReset_Click;
            btnReportFirst.Click += BtnReportFirst_Click;
            btnReportPrev.Click += BtnReportPrev_Click;
            btnReportNext.Click += BtnReportNext_Click;
            btnReportLast.Click += BtnReportLast_Click;
            cboReportPageSize.SelectedIndexChanged += CboReportPageSize_SelectedIndexChanged;
            btnReportBatchDelete.Click += BtnReportBatchDelete_Click;
            btnReportExport.Click += BtnReportExport_Click;
            
            // 绑定筛选框的事件
            txtProductionOrdersCode.KeyPress += TxtProductionOrdersCode_KeyPress;
            txtProductionOrdersCode.Enter += TxtProductionOrdersCode_Enter;
            txtProductionOrdersCode.Leave += TxtProductionOrdersCode_Leave;
            
            // 绑定菜单事件
            menuProcess.Click += MenuProcess_Click;
            menuReport.Click += MenuReport_Click;
            menuRefresh.Click += MenuRefresh_Click;
            生产工单ToolStripMenuItem.Click += 生产工单ToolStripMenuItem_Click;
            
            // 设置窗体标题
            this.Text = "生产工单管理系统";
            
            // 设置RichTextBox右键菜单
            SetupRichTextBoxContextMenu();

            // 初始化生产工单界面
            InitializeOrdersControls();
        }

        private void InitializeOrdersControls()
        {
            panelOrders = new Panel { Dock = DockStyle.Fill, Visible = false };
            panelOrdersFilter = new Panel { Dock = DockStyle.Top, Height = 50 };
            panelOrdersPaging = new Panel { Dock = DockStyle.Bottom, Height = 50 };
            dgvOrders = new DataGridView
            {
                Dock = DockStyle.Fill,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                BackgroundColor = Color.White,
                RowHeadersVisible = false,
                ScrollBars = ScrollBars.Both
            };

            // 过滤区控件
            txtOrdersCode = new TextBox { Width = 110, Text = "输入工单编号", Location = new Point(90, 12) };
            var lblOC = new Label { Text = "工单编号:", Location = new Point(10, 15), AutoSize = true };
            txtOrdersName = new TextBox { Width = 110, Text = "输入工单名称", Location = new Point(300, 12) };
            var lblON = new Label { Text = "工单名称:", Location = new Point(220, 15), AutoSize = true };
            txtOrdersProductName = new TextBox { Width = 110, Text = "输入产品名称", Location = new Point(510, 12) };
            var lblPN = new Label { Text = "产品名称:", Location = new Point(430, 15), AutoSize = true };
            cboOrdersState = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Location = new Point(700, 12), Width = 100 };
            var lblOS = new Label { Text = "状态:", Location = new Point(650, 15), AutoSize = true };
            cboOrdersState.Items.AddRange(new object[] { "请选择", "待排产", "未开始", "进行中", "已完成", "已暂停", "已关闭" });
            cboOrdersState.SelectedIndex = 0;
            btnOrdersSearch = new Button { Text = "搜索", Location = new Point(820, 10), Width = 60, Height = 30 };
            btnOrdersReset = new Button { Text = "重置", Location = new Point(890, 10), Width = 60, Height = 30 };
            btnOrdersSchedule = new Button { Text = "排产", Location = new Point(960, 10), Width = 60, Height = 30 };

            btnOrdersSearch.Click += (s, e) =>
            {
                if (isLoading) return;
                ordersFilterCode = GetFilterValue(txtOrdersCode, "输入工单编号");
                ordersFilterName = GetFilterValue(txtOrdersName, "输入工单名称");
                ordersFilterProductName = GetFilterValue(txtOrdersProductName, "输入产品名称");
                ordersFilterState = GetOrdersStateFilterValue();
                currentPageIndex = 1;
                _ = LoadProductionOrdersAsync();
            };

            btnOrdersReset.Click += (s, e) =>
            {
                if (isLoading) return;
                txtOrdersCode.Text = "输入工单编号";
                txtOrdersName.Text = "输入工单名称";
                txtOrdersProductName.Text = "输入产品名称";
                cboOrdersState.SelectedIndex = 0;
                ordersFilterCode = ordersFilterName = ordersFilterProductName = ordersFilterState = "";
                currentPageIndex = 1;
                _ = LoadProductionOrdersAsync();
            };

            panelOrdersFilter.Controls.AddRange(new Control[] { lblOC, txtOrdersCode, lblON, txtOrdersName, lblPN, txtOrdersProductName, lblOS, cboOrdersState, btnOrdersSearch, btnOrdersReset, btnOrdersSchedule });

            // 占位符与回车搜索
            SetupOrdersPlaceholder(txtOrdersCode, "输入工单编号");
            SetupOrdersPlaceholder(txtOrdersName, "输入工单名称");
            SetupOrdersPlaceholder(txtOrdersProductName, "输入产品名称");

            // 分页区
            lblOrdersTotal = new Label { Location = new Point(10, 15), AutoSize = true, Text = "共0条" };
            lblOrdersPage = new Label { Location = new Point(80, 15), AutoSize = true, Text = "第1页/共1页" };
            btnOrdersFirst = new Button { Text = "首页", Location = new Point(180, 10), Width = 50, Height = 30 };
            btnOrdersPrev = new Button { Text = "上页", Location = new Point(240, 10), Width = 50, Height = 30 };
            btnOrdersNext = new Button { Text = "下页", Location = new Point(300, 10), Width = 50, Height = 30 };
            btnOrdersLast = new Button { Text = "末页", Location = new Point(360, 10), Width = 50, Height = 30 };
            cboOrdersPageSize = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Location = new Point(420, 12), Width = 60 };
            cboOrdersPageSize.Items.AddRange(new object[] { "15", "30", "50", "100" });
            cboOrdersPageSize.SelectedIndex = 0;

            btnOrdersFirst.Click += (s, e) => { if (isLoading) return; currentPageIndex = 1; _ = LoadProductionOrdersAsync(); };
            btnOrdersPrev.Click += (s, e) => { if (isLoading) return; if (currentPageIndex > 1) { currentPageIndex--; _ = LoadProductionOrdersAsync(); } };
            btnOrdersNext.Click += (s, e) => { if (isLoading) return; if (currentPageIndex < totalPage) { currentPageIndex++; _ = LoadProductionOrdersAsync(); } };
            btnOrdersLast.Click += (s, e) => { if (isLoading) return; currentPageIndex = totalPage; _ = LoadProductionOrdersAsync(); };
            cboOrdersPageSize.SelectedIndexChanged += (s, e) => { if (isLoading) return; pageSize = int.Parse(cboOrdersPageSize.SelectedItem.ToString()); currentPageIndex = 1; _ = LoadProductionOrdersAsync(); };

            panelOrdersPaging.Controls.AddRange(new Control[] { lblOrdersTotal, lblOrdersPage, btnOrdersFirst, btnOrdersPrev, btnOrdersNext, btnOrdersLast, cboOrdersPageSize });

            panelOrders.Controls.Add(dgvOrders);
            panelOrders.Controls.Add(panelOrdersFilter);
            panelOrders.Controls.Add(panelOrdersPaging);

            // 插入到主容器
            panelMain.Controls.Add(panelOrders);

            btnOrdersSchedule.Click += (s, e) =>
            {
                if (isLoading) return;
                if (dgvOrders?.DataSource is List<ProductionOrders> orders && dgvOrders.CurrentRow != null)
                {
                    var current = dgvOrders.CurrentRow.DataBoundItem as ProductionOrders;
                    using (var dlg = new ScheduleForm(current))
                    {
                        if (dlg.ShowDialog(this) == DialogResult.OK)
                        {
                            // 排产成功后，立即刷新数据以显示状态变化
                            _ = LoadProductionOrdersAsync();
                            // 强制刷新当前行的显示
                            RefreshOrdersDisplay();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请先选择一条生产工单", "排产", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            };
        }



        // 工单编号筛选框事件处理
        private void TxtProductionOrdersCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                _ = LoadReportsAsync();
            }
        }

        private void TxtProductionOrdersCode_Enter(object sender, EventArgs e)
        {
            if (txtProductionOrdersCode.Text == "输入检验单号")
            {
                txtProductionOrdersCode.Text = "";
                txtProductionOrdersCode.ForeColor = Color.Black;
            }
        }

        private void TxtProductionOrdersCode_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtProductionOrdersCode.Text))
            {
                txtProductionOrdersCode.Text = "输入检验单号";
                txtProductionOrdersCode.ForeColor = Color.Gray;
            }
        }









        // DataError事件处理程序，用于捕获DataGridView的格式化错误
        private void DgvReport_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            // 静默处理格式化错误，不显示错误对话框
            e.ThrowException = false;
            
            // 记录错误信息到控制台（可选）
            Console.WriteLine($"DataGridView DataError: Column={e.ColumnIndex}, Row={e.RowIndex}, Context={e.Context}, Exception={e.Exception?.Message}");
        }

        // 数据网格单元格格式化事件处理
        private void DgvReport_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && e.Value != null)
                {
                    var column = dgvReport.Columns[e.ColumnIndex];
                    
                    if (column.Name == "state") // 检验结果列
                    {
                        if (e.Value is bool boolValue)
                        {
                            e.Value = boolValue ? "合格" : "不合格";
                            e.FormattingApplied = true;
                        }
                    }
                    else if (column.Name == "inspectionDate") // 检验日期列
                    {
                        if (e.Value is DateTime dateValue)
                        {
                            e.Value = dateValue.ToString("yyyy-MM-dd HH:mm:ss");
                            e.FormattingApplied = true;
                        }
                    }
                }
            }
            catch
            {
                // 如果格式化失败，不应用格式化，让DataGridView使用默认格式
                e.FormattingApplied = false;
            }
        }

        private void DgvOrders_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                var grid = sender as DataGridView;
                var column = grid.Columns[e.ColumnIndex];
                if (column.Name == nameof(ProductionOrders.State))
                {
                    if (e.Value != null && int.TryParse(e.Value.ToString(), out int stateValue))
                    {
                        switch (stateValue)
                        {
                            case 0: e.Value = "待排产"; break;
                            case 1: e.Value = "未开始"; break;
                            case 2: e.Value = "进行中"; break;
                            case 3: e.Value = "已完成"; break;
                            case 4: e.Value = "已暂停"; break;
                            case 5: e.Value = "已关闭"; break;
                            default: e.Value = "未知"; break;
                        }
                        e.FormattingApplied = true;
                    }
                }
            }
        }

        // 操作列格式化：根据数据自动判断状态并显示按钮文本和样式
        private void DgvOrdersAction_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                var grid = sender as DataGridView;
                var column = grid.Columns[e.ColumnIndex];
                if (column.Name == "colSchedule")
                {
                    if (grid.Rows[e.RowIndex].DataBoundItem is ProductionOrders order)
                    {
                        // 根据数据自动判断状态
                        bool hasActualQuantity = order.ActualQuantity > 0;
                        bool hasActualEnd = order.ActualEnd.HasValue;
                        int state = order.State;
                        
                        string buttonText;
                        Color buttonColor;
                        
                        if (state == 0)
                        {
                            // 待排产 → 显示排产
                            buttonText = "排产";
                            buttonColor = Color.LightBlue;
                        }
                        else if (hasActualEnd)
                        {
                            // 已完成 → 查看
                            buttonText = "查看";
                            buttonColor = Color.LightGray;
                        }
                        else if (hasActualQuantity)
                        {
                            // 进行中 → 排产
                            buttonText = "排产";
                            buttonColor = Color.LightBlue;
                        }
                        else
                        {
                            // 其他未知/只读 → 查看
                            buttonText = "查看";
                            buttonColor = Color.LightGray;
                        }
                        
                        // 动态设置按钮文本
                        e.Value = buttonText;
                        e.FormattingApplied = true;
                        
                        // 设置按钮样式
                        var row = grid.Rows[e.RowIndex];
                        row.Cells[e.ColumnIndex].Style.BackColor = buttonColor;
                        row.Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
                    }
                }
            }
        }

        private void CboReportPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 物料管理接口不分页，此控件已禁用
            MessageBox.Show("物料管理接口不支持分页操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void BtnReportLast_Click(object sender, EventArgs e)
        {
            // 物料管理接口不分页，此按钮已禁用
            MessageBox.Show("物料管理接口不支持分页操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void BtnReportNext_Click(object sender, EventArgs e)
        {
            // 物料管理接口不分页，此按钮已禁用
            MessageBox.Show("物料管理接口不支持分页操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void BtnReportPrev_Click(object sender, EventArgs e)
        {
            // 物料管理接口不分页，此按钮已禁用
            MessageBox.Show("物料管理接口不支持分页操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void BtnReportFirst_Click(object sender, EventArgs e)
        {
            // 物料管理接口不分页，此按钮已禁用
            MessageBox.Show("物料管理接口不支持分页操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void BtnReportReset_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            
            // 重置检验单号筛选框
            txtProductionOrdersCode.Text = "输入检验单号";
            txtProductionOrdersCode.ForeColor = Color.Gray;
            
            // 清空筛选条件
            filterInspectionOrderCode = "";
            
            currentPageIndex = 1;
            _ = LoadReportsAsync();
        }

        private async void BtnReportBatchDelete_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            if (dgvReport.SelectedRows == null || dgvReport.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的报工记录（可多选）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 物料管理接口不支持删除操作
            MessageBox.Show("物料管理接口不支持删除操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;


        }

        private void BtnReportExport_Click(object sender, EventArgs e)
        {
            if (dgvReport.DataSource is List<ProcessInspectionDto> items && items.Count > 0)
            {
                using (var sfd = new SaveFileDialog())
                {
                    sfd.Title = "导出质检数据";
                    sfd.Filter = "CSV 文件 (*.csv)|*.csv";
                    sfd.FileName = $"质检导出_{DateTime.Now:yyyyMMdd_HHmmss}.csv";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            var sb = new StringBuilder();
                            sb.AppendLine("检验单ID,检验单号,检验单名称,检验日期,检验员,生产工单号,派工ID,检验数量,合格数量,不合格数量,检验结果,产品名称,产品编码,规格型号,产品类型,单位");
                            foreach (var r in items)
                            {
                                string Escape(string v) => string.IsNullOrEmpty(v) ? "" : (v.Contains(",") || v.Contains("\"") ? $"\"{v.Replace("\"","\"\"")}\"" : v);
                                sb.AppendLine(string.Join(",", new string[]
                                {
                                    r.inspectionOrderId.ToString(),
                                    Escape(r.inspectionOrderCode),
                                    Escape(r.inspectionOrderName),
                                    r.inspectionDate.ToString("yyyy-MM-dd HH:mm:ss"),
                                    Escape(r.inspector),
                                    Escape(r.productionOrderCode),
                                    r.dispatchId.ToString(),
                                    r.inspectionQuantity.ToString(),
                                    r.qualifiedQuantity.ToString(),
                                    r.unqualifiedQuantity.ToString(),
                                    r.state ? "合格" : "不合格",
                                    Escape(r.productName),
                                    Escape(r.productCode),
                                    Escape(r.specificationModel),
                                    Escape(r.productType),
                                    Escape(r.unit)
                                }));
                            }
                            System.IO.File.WriteAllText(sfd.FileName, sb.ToString(), Encoding.UTF8);
                            MessageBox.Show("导出成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"导出失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("当前没有可导出的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BtnReportSearch_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            
            // 获取检验单号筛选值
            var rawInspectionOrderCode = txtProductionOrdersCode.Text.Trim();
            Console.WriteLine($"原始输入值: 检验单号='{rawInspectionOrderCode}'");
            
            // 获取检验单号筛选值
            filterInspectionOrderCode = GetFilterValue(txtProductionOrdersCode, "输入检验单号");
            
            // 添加调试信息
            Console.WriteLine($"处理后的筛选条件: 检验单号='{filterInspectionOrderCode}'");
            Console.WriteLine($"筛选条件是否为空: 检验单号={string.IsNullOrEmpty(filterInspectionOrderCode)}");
            
            MessageBox.Show($"正在搜索:\n检验单号: {filterInspectionOrderCode}", "搜索信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            currentPageIndex = 1;
            _ = LoadReportsAsync();
        }
        
        private string GetFilterValue(TextBox textBox, string placeholder)
        {
            var text = textBox.Text.Trim();
            // 修复筛选值获取逻辑：只有当文本完全等于占位符时才返回空字符串
            // 如果用户输入了实际内容（即使是"0545"这样的值），应该保留
            if (text == placeholder || string.IsNullOrWhiteSpace(text))
            {
                return "";
            }
            return text;
        }



        private void MenuProcess_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            showingOrders = false;
            ShowProcessPanel();
            _ = LoadProcessesAsync();
        }

        private void MenuReport_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            ShowReportPanel();
            _ = LoadReportsAsync();
        }

        private void MenuRefresh_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            if (showingOrders)
            {
                _ = LoadProductionOrdersAsync();
            }
            else if (panelProcess.Visible)
            {
                _ = LoadProcessesAsync();
            }
            else
            {
                _ = LoadReportsAsync();
            }
        }

        private void 生产工单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (isLoading) return;
            showingOrders = true;
            ShowOrdersPanel();
            _ = LoadProductionOrdersAsync();
        }

        private void ShowProcessPanel()
        {
            panelProcess.Visible = true;
            panelReport.Visible = false;
            if (panelOrders != null) panelOrders.Visible = false;
        }

        private void ShowReportPanel()
        {
            panelProcess.Visible = false;
            panelReport.Visible = true;
            if (panelOrders != null) panelOrders.Visible = false;
        }

        private void ShowOrdersPanel()
        {
            panelProcess.Visible = false;
            panelReport.Visible = false;
            if (panelOrders != null) panelOrders.Visible = true;
        }

        private void SetupRichTextBoxContextMenu()
        {
            var contextMenu = new ContextMenuStrip();
            
            var copyItem = new ToolStripMenuItem("复制");
            copyItem.Click += (sender, e) => rtbProcess.Copy();
            
            var selectAllItem = new ToolStripMenuItem("全选");
            selectAllItem.Click += (sender, e) => rtbProcess.SelectAll();
            
            var clearItem = new ToolStripMenuItem("清空");
            clearItem.Click += (sender, e) => rtbProcess.Clear();
            
            var refreshItem = new ToolStripMenuItem("刷新数据");
            refreshItem.Click += (sender, e) => _ = LoadProcessesAsync();
            
            contextMenu.Items.AddRange(new ToolStripItem[]
            {
                copyItem,
                selectAllItem,
                new ToolStripSeparator(),
                clearItem,
                refreshItem
            });
            
            rtbProcess.ContextMenuStrip = contextMenu;
            
            // 设置RichTextBox样式
            rtbProcess.BackColor = Color.White;
            rtbProcess.BorderStyle = BorderStyle.None;
            rtbProcess.Font = new Font("Consolas", 9, FontStyle.Regular);
            rtbProcess.ReadOnly = true;
            rtbProcess.WordWrap = false;
            rtbProcess.ScrollBars = RichTextBoxScrollBars.Both;
            rtbProcess.KeyDown += RtbProcess_KeyDown;
        }

        private void RtbProcess_KeyDown(object sender, KeyEventArgs e)
        {
            if (!panelProcess.Visible || !showingOrders || isLoading) return;
            if (e.KeyCode == Keys.Right || e.KeyCode == Keys.PageDown)
            {
                if (currentPageIndex < totalPage)
                {
                    currentPageIndex++;
                    _ = LoadProductionOrdersAsync();
                }
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Left || e.KeyCode == Keys.PageUp)
            {
                if (currentPageIndex > 1)
                {
                    currentPageIndex--;
                    _ = LoadProductionOrdersAsync();
                }
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Home)
            {
                if (currentPageIndex != 1)
                {
                    currentPageIndex = 1;
                    _ = LoadProductionOrdersAsync();
                }
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.End)
            {
                if (currentPageIndex != totalPage && totalPage > 0)
                {
                    currentPageIndex = totalPage;
                    _ = LoadProductionOrdersAsync();
                }
                e.Handled = true;
            }
        }

        private void SetupOrdersPlaceholder(TextBox textBox, string placeholder)
        {
            textBox.ForeColor = Color.Gray;
            textBox.Enter += (s, e) =>
            {
                if (textBox.Text == placeholder)
                {
                    textBox.Text = "";
                    textBox.ForeColor = Color.Black;
                }
            };
            textBox.Leave += (s, e) =>
            {
                if (string.IsNullOrWhiteSpace(textBox.Text))
                {
                    textBox.Text = placeholder;
                    textBox.ForeColor = Color.Gray;
                }
            };
            textBox.KeyPress += (s, e) =>
            {
                if (e.KeyChar == (char)Keys.Enter)
                {
                    e.Handled = true;
                    btnOrdersSearch.PerformClick();
                }
            };
        }

        private void UpdatePagingInfo()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(UpdatePagingInfo));
                return;
            }

            lblReportTotal.Text = $"共{totalCount}条";
            lblReportPage.Text = "第1页/共1页"; // 物料管理接口不分页

            // 物料管理接口不分页，禁用分页按钮
            btnReportFirst.Enabled = false;
            btnReportPrev.Enabled = false;
            btnReportNext.Enabled = false;
            btnReportLast.Enabled = false;
            
            // 添加调试信息
            Console.WriteLine($"分页信息更新: 总数={totalCount}, 当前页=1, 总页数=1");
            Console.WriteLine($"分页按钮禁用状态: 首页=false, 上页=false, 下页=false, 末页=false");
        }

        private void UpdateLoadingState(bool loading)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<bool>(UpdateLoadingState), loading);
                return;
            }

            // 更新控件状态
            btnReportSearch.Enabled = !loading;
            btnReportReset.Enabled = !loading;
            btnReportBatchDelete.Enabled = !loading;
            cboReportPageSize.Enabled = false; // 物料管理接口不分页
            txtProductionOrdersCode.Enabled = !loading;
            
            // 更新菜单状态
            menuProcess.Enabled = !loading;
            menuReport.Enabled = !loading;
            menuRefresh.Enabled = !loading;
            // 订单过滤控件
            if (panelOrders != null)
            {
                if (btnOrdersSearch != null) btnOrdersSearch.Enabled = !loading;
                if (btnOrdersReset != null) btnOrdersReset.Enabled = !loading;
                if (btnOrdersFirst != null) btnOrdersFirst.Enabled = !loading;
                if (btnOrdersPrev != null) btnOrdersPrev.Enabled = !loading;
                if (btnOrdersNext != null) btnOrdersNext.Enabled = !loading;
                if (btnOrdersLast != null) btnOrdersLast.Enabled = !loading;
                if (cboOrdersPageSize != null) cboOrdersPageSize.Enabled = !loading;
                if (txtOrdersCode != null) txtOrdersCode.Enabled = !loading;
                if (txtOrdersName != null) txtOrdersName.Enabled = !loading;
                if (txtOrdersProductName != null) txtOrdersProductName.Enabled = !loading;
                if (cboOrdersState != null) cboOrdersState.Enabled = !loading;
            }
            
            // 更新窗体标题显示加载状态
            if (loading)
            {
                this.Text = "生产工单管理系统 - 加载中...";
            }
            else
            {
                this.Text = "生产工单管理系统";
            }
        }

        private async Task LoadProcessesAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            if (isLoading) return;
            isLoading = true;
            UpdateLoadingState(true);
            
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var requestUrl = urls+"/api/ProductionOrders/ProcessTableCommand";
                    var response = await httpClient.GetAsync(requestUrl, cancellationToken).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

                    var json = await response.Content.ReadAsStringAsync();

                    var apiEnvelope = JsonConvert.DeserializeObject<SimpleApiResponse<List<ProcessTable>>>(json);
                    var items = apiEnvelope?.data ?? new List<ProcessTable>();

                    Invoke(new Action(() =>
                    {
                        // 清空文本框
                        rtbProcess.Clear();
                        
                        if (items.Count == 0)
                        {
                            rtbProcess.AppendText("暂无工序数据");
                            return;
                        }
                        
                        // 添加标题
                        rtbProcess.SelectionFont = new Font("Microsoft YaHei", 14, FontStyle.Bold);
                        rtbProcess.SelectionColor = Color.DarkBlue;
                        rtbProcess.AppendText("📋 工序信息列表\n");
                        rtbProcess.SelectionFont = new Font("Microsoft YaHei", 10, FontStyle.Regular);
                        rtbProcess.SelectionColor = Color.Gray;
                        rtbProcess.AppendText("=".PadRight(60, '=') + "\n\n");
                        
                        // 设置表头样式
                        rtbProcess.SelectionFont = new Font("Consolas", 10, FontStyle.Bold);
                        rtbProcess.SelectionColor = Color.Black;
                        
                        // 添加表头
                        string header = string.Format("{0,-8} {1,-12} {2,-15} {3,-8} {4,-20} {5,-20}\n",
                            "🔢 工序ID", "📝 工序编号", "🏭 工序名称", "📊 状态", "📄 工序说明", "💬 备注");
                        rtbProcess.AppendText(header);
                        rtbProcess.SelectionColor = Color.DarkGray;
                        rtbProcess.AppendText("─".PadRight(120, '─') + "\n");
                        
                        // 设置数据样式
                        rtbProcess.SelectionFont = new Font("Consolas", 9, FontStyle.Regular);
                        
                        // 添加数据行
                        foreach (var item in items)
                        {
                            AppendProcessRow(rtbProcess, item);
                        }
                        
                        // 添加统计信息
                        rtbProcess.AppendText("\n" + "─".PadRight(120, '─') + "\n");
                        rtbProcess.SelectionFont = new Font("Microsoft YaHei", 9, FontStyle.Italic);
                        rtbProcess.SelectionColor = Color.Gray;
                        rtbProcess.AppendText($"📊 共 {items.Count} 条工序记录\n");
                        rtbProcess.AppendText($"🕒 更新时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                    }));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载工序失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isLoading = false;
                UpdateLoadingState(false);
            }
        }

        private async Task LoadReportsAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            if (isLoading) return;
            isLoading = true;
            UpdateLoadingState(true);
            
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var requestUrl = "http://10.223.8.23:8008/api/ProcessInspection/GetProcessInspection";
                    
                    // 根据物料管理质检接口的筛选参数
                    if (!string.IsNullOrEmpty(filterInspectionOrderCode))
                    {
                        requestUrl += $"?inspectionOrderCode={Uri.EscapeDataString(filterInspectionOrderCode)}";
                    }
                    
                    // 添加调试信息
                    Console.WriteLine($"请求URL: {requestUrl}");
                    Console.WriteLine($"当前页: {currentPageIndex}, 页大小: {pageSize}");
                    Console.WriteLine($"筛选条件: 检验单号='{filterInspectionOrderCode}'");
                    
                    var response = await httpClient.GetAsync(requestUrl, cancellationToken).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

                    var json = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"API响应JSON: {json}");

                    // 使用物料管理的API响应格式
                    var apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse<ProcessInspectionDto>>(json);
                    
                    if (apiResponse != null && apiResponse.code == 200)
                    {
                        var items = apiResponse.data ?? new List<ProcessInspectionDto>();
                        totalCount = items.Count;
                        totalPage = 1; // 物料管理接口不分页
                    
                        // 添加调试信息
                        Console.WriteLine($"API响应成功: 总数={totalCount}, 当前页数据条数={items.Count}");

                        // 更新分页信息显示
                        UpdatePagingInfo();



                    Invoke(new Action(() =>
                        {
                            dgvReport.DataSource = items;
                            
                            // 设置DataGridView的自动调整模式
                            dgvReport.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                            dgvReport.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                            
                            // 设置交替行颜色
                            dgvReport.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
                            dgvReport.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
                            dgvReport.DefaultCellStyle.SelectionForeColor = Color.Black;
                            
                            if (dgvReport.Columns.Count > 0)
                            {
                                // 添加“查看”操作列
                                const string colName = "colReportView";
                                if (!dgvReport.Columns.Contains(colName))
                                {
                                    var col = new DataGridViewButtonColumn
                                    {
                                        Name = colName,
                                        HeaderText = "操作",
                                        Text = "查看",
                                        UseColumnTextForButtonValue = true,
                                        Width = 70,
                                        AutoSizeMode = DataGridViewAutoSizeColumnMode.None
                                    };
                                    dgvReport.Columns.Add(col);
                                    dgvReport.CellContentClick += DgvReport_CellContentClick;
                                }

                                // 动态创建列并设置正确的DataPropertyName
                                dgvReport.Columns.Clear();
                                
                                // 创建所有需要的列
                                var columns = new[]
                                {
                                    new { Name = "inspectionOrderName", HeaderText = "检验单名称", Width = 150, DataPropertyName = "inspectionOrderName" },
                                    new { Name = "inspectionOrderCode", HeaderText = "检验单号", Width = 150, DataPropertyName = "inspectionOrderCode" },
                                    new { Name = "productName", HeaderText = "产品名称", Width = 150, DataPropertyName = "productName" },
                                    new { Name = "productCode", HeaderText = "产品编号", Width = 150, DataPropertyName = "productCode" },
                                    new { Name = "specificationModel", HeaderText = "规格型号", Width = 150, DataPropertyName = "specificationModel" },
                                    new { Name = "unit", HeaderText = "单位", Width = 150, DataPropertyName = "unit" },
                                    new { Name = "productType", HeaderText = "产品类型", Width = 150, DataPropertyName = "productType" },
                                    new { Name = "inspectionDate", HeaderText = "检验日期", Width = 150, DataPropertyName = "inspectionDate" },
                                    new { Name = "inspector", HeaderText = "检验人", Width = 110, DataPropertyName = "inspector" },
                                    new { Name = "inspectionQuantity", HeaderText = "检测数量", Width = 150, DataPropertyName = "inspectionQuantity" },
                                    new { Name = "qualifiedQuantity", HeaderText = "合格数量", Width = 150, DataPropertyName = "qualifiedQuantity" },
                                    new { Name = "unqualifiedQuantity", HeaderText = "不合格数量", Width = 150, DataPropertyName = "unqualifiedQuantity" },
                                    new { Name = "state", HeaderText = "检验结果", Width = 150, DataPropertyName = "state" }
                                };

                                foreach (var col in columns)
                                {
                                    var column = new DataGridViewTextBoxColumn
                                    {
                                        Name = col.Name,
                                        HeaderText = col.HeaderText,
                                        Width = col.Width,
                                        DataPropertyName = col.DataPropertyName,
                                        AutoSizeMode = DataGridViewAutoSizeColumnMode.None
                                    };
                                    dgvReport.Columns.Add(column);
                                }

                                // 列宽已在创建列时设置

                                // 隐藏审计字段（创建人、创建时间等）
                                if (dgvReport.Columns.Contains("CreateBy"))
                                    dgvReport.Columns["CreateBy"].Visible = false;
                                if (dgvReport.Columns.Contains("CreateTime"))
                                    dgvReport.Columns["CreateTime"].Visible = false;
                                if (dgvReport.Columns.Contains("UpdBy"))
                                    dgvReport.Columns["UpdBy"].Visible = false;
                                if (dgvReport.Columns.Contains("UpdTime"))
                                    dgvReport.Columns["UpdTime"].Visible = false;
                                if (dgvReport.Columns.Contains("IsDel"))
                                    dgvReport.Columns["IsDel"].Visible = false;

                                // 添加DataError事件处理程序来捕获格式化错误
                                dgvReport.DataError += DgvReport_DataError;
                                
                                // 添加CellFormatting事件处理程序来格式化显示
                                dgvReport.CellFormatting += DgvReport_CellFormatting;
                            }
                        }));
                    }
                    else
                    {
                        var errorMessage = apiResponse?.message ?? "未知错误";
                        if (apiResponse?.code != 200)
                        {
                            MessageBox.Show($"加载报工失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载报工失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isLoading = false;
                UpdateLoadingState(false);
            }
        }

        private string GetOrdersStateFilterValue()
        {
            if (cboOrdersState == null || cboOrdersState.SelectedIndex <= 0) return "";
            switch (cboOrdersState.SelectedIndex)
            {
                case 1: return "0"; // 待排产
                case 2: return "1"; // 未开始
                case 3: return "2"; // 进行中
                case 4: return "3"; // 已完成
                case 5: return "4"; // 已暂停
                case 6: return "5"; // 已关闭
            }
            return "";
        }

        private async Task LoadProductionOrdersAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            if (isLoading) return;
            isLoading = true;
            UpdateLoadingState(true);

            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var requestUrl = urls+$"/api/ProductionOrders/ProductionOrdersCommand?PageIndex={currentPageIndex}&PageSize={pageSize}";
                    if (!string.IsNullOrEmpty(ordersFilterCode)) requestUrl += $"&ProductionOrdersCode={Uri.EscapeDataString(ordersFilterCode)}";
                    if (!string.IsNullOrEmpty(ordersFilterName)) requestUrl += $"&ProductionOrdersName={Uri.EscapeDataString(ordersFilterName)}";
                    if (!string.IsNullOrEmpty(ordersFilterProductName)) requestUrl += $"&ProductName={Uri.EscapeDataString(ordersFilterProductName)}";
                    if (!string.IsNullOrEmpty(ordersFilterState)) requestUrl += $"&State={Uri.EscapeDataString(ordersFilterState)}";
                    var response = await httpClient.GetAsync(requestUrl, cancellationToken).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

                    var json = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"ProductionOrders JSON: {json}");
                    var apiEnvelope = JsonConvert.DeserializeObject<ProductionOrdersApiResponse>(json);

                    var data = apiEnvelope?.data;
                    var items = data?.pageDatas ?? data?.data ?? new List<ProductionOrders>();
                    // 尝试补齐计划编号等可能命名不一致的字段
                    try
                    {
                        if ((items?.Count ?? 0) > 0)
                        {
                            var root = JObject.Parse(json);
                            var arr = (root["data"]["pageDatas"] ?? root["data"]["data"]) as JArray;
                            if (arr != null)
                            {
                                for (int i = 0; i < items.Count && i < arr.Count; i++)
                                {
                                    var t = arr[i];
                                    string planNo = (string)(t["planNumber"] ?? t["planNo"] ?? t["planCode"] ?? t["PlanNumber"] ?? t["PlanNo"] ?? t["PlanCode"]);
                                    if (!string.IsNullOrWhiteSpace(planNo))
                                    {
                                        items[i].PlanNumber = planNo;
                                    }
                                }
                            }
                        }
                    }
                    catch { /* 忽略补齐过程中的容错异常 */ }
                    totalCount = data?.totalCount ?? (items?.Count ?? 0);
                    totalPage = data?.totalPage ?? (totalCount > 0 ? (int)Math.Ceiling(totalCount / (double)pageSize) : 0);

                    Invoke(new Action(() =>
                    {
                        ShowOrdersPanel();
                        dgvOrders.DataSource = items;
                        dgvOrders.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                        dgvOrders.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
                        dgvOrders.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
                        dgvOrders.DefaultCellStyle.SelectionForeColor = Color.Black;

                        LocalizeOrdersHeaders();
                        EnsureOrdersActionColumn();
                        
                        // 在操作列添加后，再调整其他列的宽度
                        dgvOrders.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                        
                        // 调试信息：检查操作列是否正确显示
                        Console.WriteLine($"数据加载完成，总列数: {dgvOrders.Columns.Count}");
                        if (dgvOrders.Columns.Contains("colSchedule"))
                        {
                            var actionCol = dgvOrders.Columns["colSchedule"];
                            Console.WriteLine($"操作列信息: 名称={actionCol.Name}, 可见={actionCol.Visible}, 宽度={actionCol.Width}, 位置={actionCol.DisplayIndex}");
                        }
                        else
                        {
                            Console.WriteLine("警告：操作列不存在！");
                        }
                        
                        // 检查所有列的可见性
                        Console.WriteLine("所有列信息:");
                        for (int i = 0; i < dgvOrders.Columns.Count; i++)
                        {
                            var col = dgvOrders.Columns[i];
                            Console.WriteLine($"列{i}: {col.Name}, 可见={col.Visible}, 宽度={col.Width}, 位置={col.DisplayIndex}");
                        }

                        lblOrdersTotal.Text = $"共{totalCount}条";
                        lblOrdersPage.Text = $"第{currentPageIndex}页/共{totalPage}页";
                        UpdateOrdersPagingButtons();
                    }));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载生产工单失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isLoading = false;
                UpdateLoadingState(false);
            }
        }

        private void HideIfExists(DataGridView grid, string columnName)
        {
            if (grid.Columns.Contains(columnName)) grid.Columns[columnName].Visible = false;
        }

        private void UpdateOrdersPagingButtons()
        {
            bool hasData = totalCount > 0;
            bool canGoFirst = currentPageIndex > 1;
            bool canGoPrev = currentPageIndex > 1;
            bool canGoNext = hasData && currentPageIndex < totalPage;
            bool canGoLast = hasData && currentPageIndex < totalPage;
            if (btnOrdersFirst != null) btnOrdersFirst.Enabled = canGoFirst && !isLoading;
            if (btnOrdersPrev != null) btnOrdersPrev.Enabled = canGoPrev && !isLoading;
            if (btnOrdersNext != null) btnOrdersNext.Enabled = canGoNext && !isLoading;
            if (btnOrdersLast != null) btnOrdersLast.Enabled = canGoLast && !isLoading;
        }

        // 强制刷新工单表格显示
        private void RefreshOrdersDisplay()
        {
            if (dgvOrders != null)
            {
                dgvOrders.Refresh();
                // 重新绑定数据源以触发格式化事件
                var currentDataSource = dgvOrders.DataSource;
                dgvOrders.DataSource = null;
                dgvOrders.DataSource = currentDataSource;
                
                // 确保操作列正确显示
                EnsureOrdersActionColumn();
                
                // 强制刷新操作列的显示
                if (dgvOrders.Columns.Contains("colSchedule"))
                {
                    dgvOrders.Columns["colSchedule"].Visible = true;
                    dgvOrders.Columns["colSchedule"].Width = 80;
                    dgvOrders.Invalidate(); // 强制重绘
                }
            }
        }

        private void EnsureOrdersActionColumn()
        {
            if (dgvOrders == null) return;
            const string columnName = "colSchedule";
            if (!dgvOrders.Columns.Contains(columnName))
            {
                var col = new DataGridViewButtonColumn
                {
                    Name = columnName,
                    HeaderText = "操作",
                    Text = "排产",
                    UseColumnTextForButtonValue = true, // 改回true，确保按钮文本能正常显示
                    Width = 80, // 增加列宽，确保按钮完整显示
                    AutoSizeMode = DataGridViewAutoSizeColumnMode.None,
                    FlatStyle = FlatStyle.Flat, // 设置按钮样式
                    Resizable = DataGridViewTriState.False // 禁止调整列宽
                };
                dgvOrders.Columns.Add(col);
                dgvOrders.CellContentClick += DgvOrders_CellContentClick;
                dgvOrders.CellFormatting += DgvOrdersAction_CellFormatting; // 添加操作列的格式化事件
                
                Console.WriteLine($"操作列已添加: {columnName}, 列数: {dgvOrders.Columns.Count}");
            }
            else
            {
                Console.WriteLine($"操作列已存在: {columnName}");
                // 确保现有操作列可见
                var existingCol = dgvOrders.Columns[columnName];
                existingCol.Visible = true;
                existingCol.Width = 80;
            }
        }

        private void DgvOrders_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var grid = sender as DataGridView;
            var columnName = grid.Columns[e.ColumnIndex].Name;
            
            if (columnName == "colSchedule")
            {
                if (grid.Rows[e.RowIndex].DataBoundItem is ProductionOrders current)
                {
                    // 根据数据自动判断状态
                    bool hasActualQuantity = current.ActualQuantity > 0;
                    bool hasActualEnd = current.ActualEnd.HasValue;
                    int state = current.State;
                    
                    if (state == 0)
                    {
                        // 待排产 → 打开可编辑排产窗体
                        using (var dlg = new ScheduleForm(current))
                        {
                            if (dlg.ShowDialog(this) == DialogResult.OK)
                            {
                                _ = LoadProductionOrdersAsync();
                                RefreshOrdersDisplay();
                                MessageBox.Show("数据保存成功！", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                    else if (hasActualEnd)
                    {
                        // 有实际完工时间 → 已完成状态，打开只读查看窗体
                        using (var dlg = new ScheduleForm(current, true))
                        {
                            dlg.ShowDialog(this);
                        }
                    }
                    else if (hasActualQuantity)
                    {
                        // 有实际数量 → 进行中状态，打开排产窗体
                        using (var dlg = new ScheduleForm(current))
                        {
                            if (dlg.ShowDialog(this) == DialogResult.OK)
                            {
                                // 排产成功后，立即刷新数据以显示状态变化
                                _ = LoadProductionOrdersAsync();
                                // 强制刷新当前行的显示
                                RefreshOrdersDisplay();
                                
                                // 显示保存成功提示
                                MessageBox.Show("数据保存成功！", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                    else
                    {
                        // 否则 → 查看状态，打开只读查看窗体
                        using (var dlg = new ScheduleForm(current, true))
                        {
                            dlg.ShowDialog(this);
                        }
                    }
                }
            }
        }

        // 报工列表 操作列点击 → 查看
        private void DgvReport_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var grid = sender as DataGridView;
            if (grid.Columns[e.ColumnIndex].Name == "colReportView")
            {
                if (grid.Rows[e.RowIndex].DataBoundItem is ProcessInspectionDto item)
                {
                    using (var dlg = new ProcessInspectionDetailForm(item))
                    {
                        dlg.ShowDialog(this);
                    }
                }
            }
        }

        // 简洁美观的质检详情窗体
        private class ProcessInspectionDetailForm : Form
        {
            public ProcessInspectionDetailForm(ProcessInspectionDto item)
            {
                Text = "质检详情";
                StartPosition = FormStartPosition.CenterParent;
                Size = new Size(400, 500);
                FormBorderStyle = FormBorderStyle.FixedDialog;
                MaximizeBox = false;
                MinimizeBox = false;

                var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(18) };

                var title = new Label
                {
                    Text = "质检信息",
                    Font = new Font("微软雅黑", 12, FontStyle.Bold),
                    ForeColor = Color.FromArgb(55, 71, 79),
                    AutoSize = true
                };

                var table = new TableLayoutPanel
                {
                    Dock = DockStyle.Top,
                    ColumnCount = 2,
                    RowCount = 10,
                    AutoSize = true,
                    Padding = new Padding(0, 12, 0, 0)
                };
                table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 95));
                table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));

                Label L(string t) => new Label
                {
                    Text = t,
                    AutoSize = true,
                    ForeColor = Color.Gray,
                    Font = new Font("微软雅黑", 9)
                };
                Label V(string t, bool bold = false) => new Label
                {
                    Text = t,
                    AutoSize = true,
                    ForeColor = Color.Black,
                    Font = new Font("微软雅黑", bold ? 10 : 9, bold ? FontStyle.Bold : FontStyle.Regular)
                };

                int r = 0;
                table.Controls.Add(L("检验单号"), 0, r); table.Controls.Add(V(item.inspectionOrderCode ?? "-", true), 1, r++);
                table.Controls.Add(L("检验单名称"), 0, r); table.Controls.Add(V(item.inspectionOrderName ?? "-", true), 1, r++);
                table.Controls.Add(L("产品名称"), 0, r); table.Controls.Add(V($"{item.productName}（{item.productCode}）"), 1, r++);
                table.Controls.Add(L("规格型号"), 0, r); table.Controls.Add(V(item.specificationModel ?? "-"), 1, r++);
                table.Controls.Add(L("检验员"), 0, r); table.Controls.Add(V(item.inspector ?? "-"), 1, r++);
                table.Controls.Add(L("检验数量"), 0, r); table.Controls.Add(V(item.inspectionQuantity.ToString()), 1, r++);
                table.Controls.Add(L("合格/不合格"), 0, r); table.Controls.Add(V($"{item.qualifiedQuantity}/{item.unqualifiedQuantity}"), 1, r++);
                table.Controls.Add(L("检验结果"), 0, r); table.Controls.Add(V(item.state ? "合格" : "不合格", true), 1, r++);
                table.Controls.Add(L("检验日期"), 0, r); table.Controls.Add(V(item.inspectionDate.ToString("yyyy-MM-dd HH:mm:ss")), 1, r++);
                table.Controls.Add(L("生产工单号"), 0, r); table.Controls.Add(V(item.productionOrderCode ?? "-"), 1, r++);

                var btnOk = new Button
                {
                    Text = "确定",
                    Size = new Size(90, 32),
                    BackColor = Color.FromArgb(70, 130, 180),
                    ForeColor = Color.White,
                    FlatStyle = FlatStyle.Flat,
                    Anchor = AnchorStyles.Bottom
                };
                btnOk.FlatAppearance.BorderSize = 0;
                btnOk.Click += (s, e) => Close();

                var footer = new Panel { Dock = DockStyle.Bottom, Height = 56 };
                btnOk.Location = new Point((Width - btnOk.Width) / 2 - 8, 12);
                footer.Controls.Add(btnOk);

                panel.Controls.Add(table);
                panel.Controls.Add(title);
                Controls.Add(panel);
                Controls.Add(footer);
            }
        }

        /// <summary>
        /// 处理返工请求 - 根据工单编号更新生产工单状态
        /// </summary>
        /// <param name="productionOrderCode">工单编号</param>
        public async Task HandleReworkRequestAsync(string productionOrderCode)
        {
            try
            {
                Console.WriteLine($"开始处理返工请求，工单编号: {productionOrderCode}");
                
                // 1. 根据工单编号查找生产工单
                var productionOrder = await FindProductionOrderByCodeAsync(productionOrderCode);
                if (productionOrder == null)
                {
                    MessageBox.Show($"未找到工单编号为 {productionOrderCode} 的生产工单！\n\n请确认：\n1. 工单编号是否正确\n2. 生产工单是否存在于系统中", 
                        "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                Console.WriteLine($"找到生产工单: ID={productionOrder.ProductionOrdersId}, 当前状态={productionOrder.State}");
                Console.WriteLine($"工单详情: 编号={productionOrder.ProductionOrdersCode}, 名称={productionOrder.ProductionOrdersName}");

                // 2. 更新生产工单状态
                bool updateSuccess = await UpdateProductionOrderForReworkAsync(productionOrder);
                                                 if (updateSuccess)
                {
                    MessageBox.Show($"工单 {productionOrderCode} 返工处理成功！\n\n已更新：\n- 实际数量：0\n- 实际完工：清空\n- 状态：待排产\n- 备注：返工", 
                        "返工成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 不刷新生产工单列表，因为用户不在生产工单页面
                }
                else
                {
                    MessageBox.Show($"工单 {productionOrderCode} 返工处理失败！\n\n可能的原因：\n1. 网络连接问题\n2. 服务器端验证失败\n3. 工单状态不允许修改\n\n请查看控制台日志获取详细错误信息。", 
                        "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理返工请求时发生异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                MessageBox.Show($"处理返工请求时发生错误: {ex.Message}\n\n请查看控制台日志获取详细错误信息。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 根据工单编号查找生产工单
        /// </summary>
        /// <param name="productionOrderCode">工单编号</param>
        /// <returns>生产工单对象，如果未找到则返回null</returns>
        private async Task<ProductionOrders> FindProductionOrderByCodeAsync(string productionOrderCode)
        {
            try
            {
                // 搜索所有页面，直到找到目标工单
                int pageIndex = 1;
                int pageSize = 100;
                int totalSearched = 0;
                
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    
                    while (pageIndex <= 10) // 最多搜索10页
                    {
                        var requestUrl = urls+$"/api/ProductionOrders/ProductionOrdersCommand?PageIndex={pageIndex}&PageSize={pageSize}";
                        Console.WriteLine($"正在搜索工单编号: {productionOrderCode}，第{pageIndex}页");
                        
                        var response = await httpClient.GetAsync(requestUrl);
                        if (response.IsSuccessStatusCode)
                        {
                            var json = await response.Content.ReadAsStringAsync();
                            var apiEnvelope = JsonConvert.DeserializeObject<ProductionOrdersApiResponse>(json);
                            
                            var data = apiEnvelope?.data;
                            var items = data?.pageDatas ?? data?.data ?? new List<ProductionOrders>();
                            
                            if (items.Count > 0)
                            {
                                totalSearched += items.Count;
                                Console.WriteLine($"第{pageIndex}页找到 {items.Count} 个工单，累计搜索 {totalSearched} 个工单");
                                
                                var targetOrder = items.FirstOrDefault(p => p.ProductionOrdersCode == productionOrderCode);
                                if (targetOrder != null)
                                {
                                    Console.WriteLine($"找到目标工单: ID={targetOrder.ProductionOrdersId}, 编号={targetOrder.ProductionOrdersCode}, 名称={targetOrder.ProductionOrdersName}");
                                    return targetOrder;
                                }
                                
                                // 打印当前页面的工单编号用于调试
                                Console.WriteLine($"第{pageIndex}页工单编号列表: {string.Join(", ", items.Select(p => p.ProductionOrdersCode))}");
                                
                                // 如果当前页数据少于pageSize，说明已经是最后一页
                                if (items.Count < pageSize)
                                {
                                    Console.WriteLine($"第{pageIndex}页数据少于{pageSize}条，已到达最后一页");
                                    break;
                                }
                            }
                            else
                            {
                                Console.WriteLine($"第{pageIndex}页没有数据");
                                break; // 没有数据了，停止搜索
                            }
                        }
                        else
                        {
                            var errorContent = await response.Content.ReadAsStringAsync();
                            Console.WriteLine($"搜索工单失败: {response.StatusCode}, 错误内容: {errorContent}");
                            break;
                        }
                        
                        pageIndex++;
                    }
                }
                
                Console.WriteLine($"未找到工单编号: {productionOrderCode}，已搜索 {totalSearched} 个工单");
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查找生产工单时发生异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return null;
            }
        }

                /// <summary>
        /// 更新生产工单为返工状态
        /// </summary>
        /// <param name="productionOrder">生产工单对象</param>
        /// <returns>更新是否成功</returns>
        private async Task<bool> UpdateProductionOrderForReworkAsync(ProductionOrders productionOrder)
        {
            try
            {
                Console.WriteLine($"开始更新生产工单为返工状态: ID={productionOrder.ProductionOrdersId}, 编号={productionOrder.ProductionOrdersCode}");
                Console.WriteLine($"当前工单状态: 实际数量={productionOrder.ActualQuantity}, 实际完工={productionOrder.ActualEnd}, 状态={productionOrder.State}");
                
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(30); // 增加超时时间
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // 构建更新请求
                    var updateCommand = new ProductionOrdersHandleCommand
                    {
                        // 基本信息
                        ProductionOrdersId = productionOrder.ProductionOrdersId,
                        ProductionOrdersCode = productionOrder.ProductionOrdersCode,
                        ProductionOrdersName = productionOrder.ProductionOrdersName,
                        
                        // 返工状态更新
                        ActualQuantity = 0, // 实际数量设为0
                        ActualEnd = "", // 实际完工时间清空（使用空字符串而不是null）
                        State = 0, // 状态设为待排产
                        ProductionOrdersProgress = 0, // 工单进度设为0
                        
                        // 保持其他字段不变
                        PlannedQuantity = productionOrder.PlannedQuantity,
                        PlanStart = productionOrder.PlanStart?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                        PlanEnd = productionOrder.PlanEnd?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                        DemandDate = productionOrder.DemandDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                        ActualStart = productionOrder.ActualStart?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                        Remark = "返工", // 备注设置为返工
                       
                       // 产品信息
                       BOM = productionOrder.BOM ?? "",
                       Type = productionOrder.Type ?? "",
                       Unit = productionOrder.Unit ?? "",
                       Version = productionOrder.Version ?? "",
                       PlanNumber = productionOrder.PlanNumber ?? "",
                       ProductCode = productionOrder.ProductCode ?? "",
                       ProductName = productionOrder.ProductName ?? "",
                       ProductType = productionOrder.ProductType ?? "",
                       AssociatePlans = productionOrder.AssociatePlans ?? "",
                       SpecificationModel = productionOrder.SpecificationModel ?? "",
                       Batch = productionOrder.Batch ?? "",
                       CreateBy = "System"
                   };

                   var jsonContent = JsonConvert.SerializeObject(updateCommand);
                   Console.WriteLine(urls+$"发送更新请求到: /api/ProductionOrders/Handle");
                   Console.WriteLine($"请求内容: {jsonContent}");
                   
                   var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                   Console.WriteLine($"开始发送POST请求...");
                   
                   var response = await httpClient.PostAsync(urls+"/api/ProductionOrders/Handle", content);
                   Console.WriteLine($"收到响应: {response.StatusCode}");
                   
                   if (response.IsSuccessStatusCode)
                   {
                       var responseContent = await response.Content.ReadAsStringAsync();
                       Console.WriteLine($"更新成功，响应内容: {responseContent}");
                       return true;
                   }
                   else
                   {
                       var errorContent = await response.Content.ReadAsStringAsync();
                       Console.WriteLine($"更新失败: HTTP {response.StatusCode}");
                       Console.WriteLine($"错误响应内容: {errorContent}");
                       Console.WriteLine(urls+$"请求URL: /api/ProductionOrders/Handle");
                       Console.WriteLine($"请求内容: {jsonContent}");
                       return false;
                   }
               }
           }
           catch (Exception ex)
           {
               Console.WriteLine($"更新生产工单时发生异常: {ex.Message}");
               Console.WriteLine($"异常类型: {ex.GetType().Name}");
               Console.WriteLine($"异常堆栈: {ex.StackTrace}");
               return false;
           }
       }

        /// <summary>
        /// 切换到生产工单面板并定位到指定工单
        /// </summary>
        /// <param name="productionOrderCode">要定位的工单编号</param>
        public async Task SwitchToProductionOrdersAndLocateAsync(string productionOrderCode)
        {
            try
            {
                // 切换到生产工单面板
                showingOrders = true;
                ShowOrdersPanel();
                
                // 设置搜索条件
                if (txtOrdersCode != null)
                {
                    txtOrdersCode.Text = productionOrderCode;
                    txtOrdersCode.ForeColor = Color.Black;
                }
                
                // 重置其他搜索条件
                if (txtOrdersName != null) txtOrdersName.Text = "输入工单名称";
                if (txtOrdersProductName != null) txtOrdersProductName.Text = "输入产品名称";
                if (cboOrdersState != null) cboOrdersState.SelectedIndex = 0;
                
                // 更新筛选参数
                ordersFilterCode = productionOrderCode;
                ordersFilterName = "";
                ordersFilterProductName = "";
                ordersFilterState = "";
                
                // 重置到第一页
                currentPageIndex = 1;
                
                // 加载生产工单数据
                await LoadProductionOrdersAsync();
                
                // 尝试定位到指定工单
                await LocateOrderInGridAsync(productionOrderCode);
                
                Console.WriteLine($"已切换到生产工单面板并搜索工单: {productionOrderCode}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"切换到生产工单面板时发生异常: {ex.Message}");
                throw;
            }
        }
        
        /// <summary>
        /// 在网格中定位到指定工单
        /// </summary>
        /// <param name="productionOrderCode">工单编号</param>
        private async Task LocateOrderInGridAsync(string productionOrderCode)
        {
            try
            {
                if (dgvOrders?.DataSource is List<ProductionOrders> orders)
                {
                    // 在当前页面中查找工单
                    var targetOrder = orders.FirstOrDefault(o => o.ProductionOrdersCode == productionOrderCode);
                    if (targetOrder != null)
                    {
                        // 找到工单，选中对应行
                        int rowIndex = orders.IndexOf(targetOrder);
                        if (rowIndex >= 0 && rowIndex < dgvOrders.Rows.Count)
                        {
                            dgvOrders.Rows[rowIndex].Selected = true;
                            dgvOrders.FirstDisplayedScrollingRowIndex = Math.Max(0, rowIndex - 5); // 滚动到选中行附近
                            Console.WriteLine($"已定位到工单: {productionOrderCode}");
                            return;
                        }
                    }
                }
                
                // 如果当前页面没找到，显示提示信息
                MessageBox.Show($"工单 {productionOrderCode} 已加载到列表中，请查看搜索结果。", "定位完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"定位工单时发生异常: {ex.Message}");
            }
        }

        private void LocalizeOrdersHeaders()
        {
            if (dgvOrders == null || dgvOrders.Columns.Count == 0) return;
            void SetHeader(string name, string text)
            {
                if (dgvOrders.Columns.Contains(name)) dgvOrders.Columns[name].HeaderText = text;
            }

            SetHeader(nameof(ProductionOrders.ProductionOrdersId), "工单主键");
            SetHeader(nameof(ProductionOrders.ProductionOrdersCode), "工单编号");
            SetHeader(nameof(ProductionOrders.ProductionOrdersName), "工单名称");
            SetHeader(nameof(ProductionOrders.ProductionOrdersProgress), "工单进度");
            SetHeader(nameof(ProductionOrders.AssociatePlans), "关联计划");
            SetHeader(nameof(ProductionOrders.PlanNumber), "计划编号");
            SetHeader(nameof(ProductionOrders.Type), "类型");
            SetHeader(nameof(ProductionOrders.ProductName), "产品名称");
            SetHeader(nameof(ProductionOrders.ProductCode), "产品编号");
            SetHeader(nameof(ProductionOrders.SpecificationModel), "规格型号");
            SetHeader(nameof(ProductionOrders.ProductType), "产品类型");
            SetHeader(nameof(ProductionOrders.Unit), "单位");
            SetHeader(nameof(ProductionOrders.BOM), "BOM");
            SetHeader(nameof(ProductionOrders.Version), "版本");
            SetHeader(nameof(ProductionOrders.PlannedQuantity), "计划数量");
            SetHeader(nameof(ProductionOrders.ActualQuantity), "实际数量");
            SetHeader(nameof(ProductionOrders.PlanStart), "计划开工");
            SetHeader(nameof(ProductionOrders.PlanEnd), "计划完工");
            SetHeader(nameof(ProductionOrders.ActualStart), "实际开工");
            SetHeader(nameof(ProductionOrders.ActualEnd), "实际完工");
            SetHeader(nameof(ProductionOrders.Batch), "生产批次");
            SetHeader(nameof(ProductionOrders.DemandDate), "需求日期");
            SetHeader(nameof(ProductionOrders.Remark), "备注");

            if (dgvOrders.Columns.Contains(nameof(ProductionOrders.State)))
            {
                dgvOrders.Columns[nameof(ProductionOrders.State)].HeaderText = "状态";
                dgvOrders.CellFormatting -= DgvOrders_CellFormatting;
                dgvOrders.CellFormatting += DgvOrders_CellFormatting;
            }

            // 确保操作列可见且位置正确
            if (dgvOrders.Columns.Contains("colSchedule"))
            {
                dgvOrders.Columns["colSchedule"].Visible = true;
                dgvOrders.Columns["colSchedule"].DisplayIndex = dgvOrders.Columns.Count - 1; // 放在最后一列
            }

            // 隐藏审计字段
            HideIfExists(dgvOrders, "CreateBy");
            HideIfExists(dgvOrders, "CreateTime");
            HideIfExists(dgvOrders, "UpdBy");
            HideIfExists(dgvOrders, "UpdTime");
            HideIfExists(dgvOrders, "IsDel");
        }
    }



}
